import React, { useCallback, useRef } from "react";
import Styles from './index.module.less';
/**
        <div className="session_box flex-left">
            <div className="name_box">上官婉儿：</div>
            <div className="r-content flex-item">
                <div className="action">(这是动作)</div>
                <div className="speak">动画的u废物和法国日光金融和价格物和法国日光金融和价格物和法国日光金融和价格物和法国日光金融和价格物和法国日光金融和价格</div>
                <div className="monologue">好地方红日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国<span className="footnote"><span>海军</span><div className="footnote-info"><div className="footnote-info-box">中国人们海军</div></div></span>org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热</div>
                <div className="explain">{'{'+'电话费菲菲姐'+'}'}</div>
            </div>
        </div>
 */

//获得段落的html格式
const getparagraphDOM = (textNode)=>{
    const outDOM = document.createElement('div');
    outDOM.className = 'session_box flex-left';
    const nameDOM = document.createElement('div');
    nameDOM.className = 'name_box';
    nameDOM.innerText = textNode;
    outDOM.appendChild(nameDOM);
    const r_contentDOM = document.createElement('div');
    r_contentDOM.className = 'r-content flex-item'
    const DIV = document.createElement('div');
    DIV.className = 'speak';
    r_contentDOM.appendChild(DIV);
    outDOM.appendChild(r_contentDOM);
    
    var oFrag = document.createDocumentFragment();
    oFrag.appendChild(outDOM);
    var bottomoutDOM = document.createElement('div');
    bottomoutDOM.className = 'session_box flex-left';
    oFrag.appendChild(bottomoutDOM);
    return {
        outDOM:outDOM,
        divDOM:DIV,
        oFrag:oFrag
    }
}
const editor_cont_classname = 'editor-cont '+Styles.editor_cont;
export default function TextEditor(){
    const DOMRef = useRef(false);
    const inputMethodState = useRef(false);
    const Reg_character = useRef(/^[^0-9\/\:?!，。·*]{1,10}：$/);//匹配名称的正则
    const on_input = useCallback((e)=>{
        if(e.type === 'compositionstart'){
            inputMethodState.current = true;
        }else if(e.type === 'compositionend'){
            inputMethodState.current = false;
        }
        if(inputMethodState.current){
            e.stopPropagation();
            return;
        }
        const selection = window.getSelection();
        const currDOM = selection.anchorNode.parentElement;
        const currnodeValue = selection.anchorNode.nodeValue;
        if(currnodeValue === null){
            //backspace键删除的时候总是留下一个br标签 需要处理下
            const brDOM = currDOM.querySelector('br');
            brDOM && brDOM.remove()
        }
        // return;
        if(currDOM.className === 'session_box flex-left'){
            //行首处理
            if(Reg_character.current.test(currnodeValue)){
                const range = selection.getRangeAt(0);
                 // 检查光标前的字符是否是叹号  
                const textNode = range.startContainer.textContent;  
                const offset = range.startOffset;
                //写的是个人物名称需要特殊处理
                const newRange = document.createRange();
                newRange.setStart(range.startContainer, offset-textNode.length); //包含叹号
                newRange.setEnd(range.startContainer,range.endOffset); // 保持结束位置不变// 创建一个新的span元素，并设置其文本内容为newRange中的内容

                const newNodes = getparagraphDOM(textNode)
                // 用span替换newRange中的内容
                newRange.deleteContents(); // 删除旧内容
                DOMRef.current.removeChild(currDOM); //删掉上次创建的多余的一个session_box的盒子

                // var oFrag=document.createDocumentFragment();
                // oFrag.appendChild(newNodes.outDOM);
                // var outDOM = document.createElement('div');
                // outDOM.className = 'session_box';
                // oFrag.appendChild(outDOM);

                newRange.insertNode(newNodes.oFrag); // 插入新的元素
                
                // 重新设置光标位置（这可能需要一些调整，因为插入span会改变DOM结构）  
                const newSelection = window.getSelection();
                const newNode = newNodes.outDOM.querySelector('.speak'); // 假设span只有一个文本节点
                const newNodeRange = document.createRange();
                newNodeRange.setStart(newNode, 0);
                newNodeRange.setEnd(newNode, newNode.textContent.length);
                newSelection.removeAllRanges();
                newSelection.addRange(newNodeRange);
            }
        }
        // else if(currnodeValue){
        //     if(currnodeValue.indexOf('*（）') !== -1){
        //         //动作
        //         currDOM.className = 'action';
        //         currDOM.innerText = '（）对方是否合法是否合法';
        //         // 重新设置光标位置（这可能需要一些调整，因为插入span会改变DOM结构）  
        //         const newSelection = window.getSelection();;
        //         const newNode = currDOM; // 假设span只有一个文本节点
        //         console.log(newNode,newNode.textContent);
        //         // console.log(111,newNode.createTextRange)
        //         // return;
        //         const newNodeRange = document.createRange();
        //         newNodeRange.setStart(newNode, 2);
        //         newNodeRange.setEnd(newNode, 3);
        //         newSelection.removeAllRanges();
        //         newSelection.addRange(newNodeRange);

        //     }
        // }
    },[])
    const on_keydown = useCallback((e)=>{
        
        const selection = window.getSelection();
        var range = selection.getRangeAt(0);
        // 获取光标后的元素
        var nextNode = range.endContainer.nextElementSibling;

        const currDOM = selection.anchorNode.parentElement;
        const currnodeValue = selection.anchorNode.nodeValue;
        // console.log(88,currDOM,e.code)
        if(e.code === 'Backspace'){
            // console.log(11,currDOM.className,currDOM.innerHTML)
            if(currDOM.className === editor_cont_classname){
                //这个代表此时已经删除到根节点了
                //富文本框中没有任何其他内容了 所以不能删除
                // console.log(22)
                //阻止默认事件
                e.preventDefault()
            }
            // if((currnodeValue === null) && (currDOM.className === 'session_box flex-left')){
            //     console.log('shun1',currDOM,currnodeValue)
            //     // DOMRef.current.removeChild(currDOM)
            //     // currDOM.remove()
            //     // if(DOMRef.current.innerHTML = ''){
            //     //     DOMRef.current.innerHTML = '<div className="session_box flex-left"></div>'
            //     // }
            // }
        }else if(e.ctrlKey){
            if(e.code === 'KeyG'){
                //动作样式
                //阻止默认事件
                e.preventDefault()
                let childNodeDOM = currDOM;
                if(currDOM.className === 'r-content flex-item'){
                    const arr = childNodeDOM.childNodes;
                    childNodeDOM = arr[arr.length-1]
                    console.log(childNodeDOM)
                }
                childNodeDOM.className = 'action';
            }else if(e.code === 'KeyH'){
                //说话样式
                //阻止默认事件
                e.preventDefault()
                let childNodeDOM = currDOM;
                if(currDOM.className === 'r-content flex-item'){
                    const arr = childNodeDOM.childNodes;
                    childNodeDOM = arr[arr.length-1]
                    console.log(childNodeDOM)
                }
                childNodeDOM.className = 'speak';
            }else if(e.code === 'KeyJ'){
                //独白
                //阻止默认事件
                e.preventDefault()
                let childNodeDOM = currDOM;
                if(currDOM.className === 'r-content flex-item'){
                    const arr = childNodeDOM.childNodes;
                    childNodeDOM = arr[arr.length-1]
                    console.log(childNodeDOM)
                }
                childNodeDOM.className = 'monologue';
            }else if(e.code === 'KeyK'){
                //备注
                //阻止默认事件
                e.preventDefault()
                let childNodeDOM = currDOM;
                if(currDOM.className === 'r-content flex-item'){
                    const arr = childNodeDOM.childNodes;
                    childNodeDOM = arr[arr.length-1]
                    console.log(childNodeDOM)
                }
                childNodeDOM.className = 'remarks';
            }else if(e.code === 'KeyL'){
                //描述
                //阻止默认事件
                e.preventDefault()
                let childNodeDOM = currDOM;
                if(currDOM.className === 'r-content flex-item'){
                    const arr = childNodeDOM.childNodes;
                    childNodeDOM = arr[arr.length-1]
                    console.log(childNodeDOM)
                }
                childNodeDOM.className = 'explain';
            }else if(e.code === 'KeyD'){
                
                //阻止默认事件
                e.preventDefault()
                let childNodeDOM = currDOM;
                const classname = childNodeDOM.parentNode.className;
                if(classname === 'r-content flex-item'){
                    childNodeDOM.parentNode.parentNode.remove()
                }else if(classname === 'session_box flex-left'){
                    childNodeDOM.parentNode.remove()
                }
            }
        } 
    },[]);
    // const on_focus = useCallback((e)=>{
    //     console.log(11,this)
    //     console.log('focus 事件',e,e.target);
    // },[])
    // const on_mouse_down = useCallback(()=>{
    // },[])
    // const on_mouse_up = useCallback(()=>{

    // },[])
    // const test_input = useCallback(()=>{
    //     console.log('a1')
    // },[])
    // const test_onchange = useCallback((e)=>{

    //     console.log('a2',e.target.value)
    // },[])
    // const testkeydown = useCallback((e)=>{
    //     console.log(e.code);
    //     if(e.code === 'KeyH'){
    //         //阻止默认事件
    //         e.preventDefault()
    //     }
    //     if(e.ctrlKey){

    //     }
    // },[])
    return (
        <>
            <div className={Styles.instruc}>
                行首xxx：代表人物名称（冒号用中文冒号）<br />
                ctrl+G动作&nbsp;&nbsp;
                ctrl+H对话&nbsp;&nbsp;
                ctrl+J场景&nbsp;&nbsp;
                ctrl+K脚注&nbsp;&nbsp;
                ctrl+L镜头&nbsp;&nbsp;
                ctrl+D删除光标所在段落
            </div>
            {/* <input type="text" onInput={test_onchange} onKeyDown={testkeydown} /> */}
            <div 
                className={'editor-cont '+Styles.editor_cont} 
                onInput={on_input} 
                onCompositionStart={on_input} 
                onCompositionEnd={on_input} 
                ref={DOMRef} 
                contentEditable="true" 
                onKeyDown={on_keydown}

                ><div className="session_box flex-left"></div></div>
            {/* <div className={Styles.cont} onMouseDown={on_mouse_down} onMouseUp={on_mouse_up} onFocus={on_focus} onInput={on_input} ref={DOMRef} contentEditable="true">
                <div className="session_box flex-left">
                    <div className="name_box">上官婉儿：</div>
                    <div className="content flex-item">
                        <div className="action">(这是动作)</div>
                        <div className="speak">动画的u废物和法国日光金融和价格物和法国日光金融和价格物和法国日光金融和价格物和法国日光金融和价格物和法国日光金融和价格</div>
                        <div className="monologue">好地方红日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国<span className="footnote"><span>海军</span><div className="footnote-info"><div className="footnote-info-box">中国人们海军</div></div></span>org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热日俄国海军org加热</div>
                        <div className="explain">{'{'+'电话费菲菲姐'+'}'}</div>
                    </div>
                </div>
            </div> */}
        </>
        
    )
}